package com.husd.leetcode.linkedlist;

/**
 * @author hushengdong@gome.com.cn
 * @date 2022/6/27 15:15
 */
public class DeleteRepeatNode {

    public static void main(String[] args) {

        Node head = init();
        System.out.println(print(head));
        head = deleteRepeatNode(head);
        System.out.println(print(head));
    }

    private static Node deleteRepeatNode(Node head) {

        if(head == null) {
            return head;
        }
        Node tempHead = new Node(-1);
        tempHead.next = head;
        Node current = tempHead.next;
        Node pre = tempHead;
        while(current != null && current.next != null) {

            // current要不要留，取决于有没有和它一样的
            Node next = current.next;
            while(same(current,next)) {
                next = next.next;
            }
            // next没有发生变化 current要留下来
            if(same(current.next,next)) {
                pre.next = current;
                pre = current;
            } else {
                pre.next = null;
            }
            current = next;
        }
        pre.next = current;
        return tempHead.next;
    }

    private static boolean same(Node n1,Node n2) {

        return n1 == n2 || (n1 != null && n2 != null && n1.val == n2.val);
    }

    private static Node init() {

        int[] arr = {1,1};
        Node head = new Node(arr[0]);
        Node current = head;
        for(int i = 1;i<arr.length;i++) {
            current.next = new Node(arr[i]);
            current = current.next;
        }
        return head;
    }

    private static String print(Node head) {

        if(head == null) {
            return "空链表";
        }
        StringBuilder sb = new StringBuilder();
        while(head != null) {
            sb.append(head.val);
            sb.append(",");
            head = head.next;
        }
        return sb.toString();
    }
}
